<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8"/>
</head>
<body>
	<!-- 脚本 -->
	<script type="text/javascript">

		var databaseName = "markReaded";
		var tableName = "markReaded";
		var database = initTable();

		function initTable() {
			var databaseVersion = "1.0";
			database = openDatabase(databaseName,
			 	databaseVersion, 
			 	databaseName, 
			 	1024*1024, 
			 	function () {});

			database.transaction(function (tx) {
					tx.executeSql("CREATE TABLE IF NOT EXISTS ? (url TEXT UNIQUE)",
						[tableName],
						function (tx, result) {
							var a = 3;
						},
						function (tx, error) {
							var a = 3;
						});
				});

			return database;
		}

		function peformCommand(event) {
			if (event.command == "markReaded") {
				markURL(event.target.browserWindow.activeTab.url);
			}
		}

		function validateCommand(event) {
			if (event.command == "markReaded") {
				// 判断网页是否为空
				event.target.disabled = !event.target.browserWindow.activeTab.url;

				// 检查url是否是曾经的
				checkURL(event.target.browserWindow.activeTab.url);
			}
		}

		function checkURL(url) {
			var newUrl = url;
			database.transaction(function (tx) {
				tx.executeSql("SELECT * FROM ? WHERE url = ?",
					[tableName, newUrl],
					function (tx, result) {
						if (result.rows.length == 1) {
							updateMarkReadedBtnState(true);
						} else {
							updateMarkReadedBtnState(false);
						}
					},
					function (tx, error) {
						updateMarkReadedBtnState(false);
					});
			});
		}

		function markURL(url) {
			var newUrl = url;
			database.transaction(function (tx) {
				tx.executeSql("INSERT INTO ? (url) values(?)",
					[tableName, url],
					function (tx, result) {
						updateMarkReadedBtnState(true);
					},
					function (tx, error) {
						
					});
			});
		}

		function updateMarkReadedBtnState(state) {
			var toolbarItems = safari.extension.toolbarItems;
			for (var i = 0; i < toolbarItems.length; i++) {
				if (toolbarItems[i].label == "markReaded") {
					toolbarItems.disabled = state;
				}
			}
		}

		safari.application.addEventListener("validate", validateCommand, false);
		safari.application.addEventListener("command", peformCommand, false);
	</script>
</body>
</html>